package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-mgr/cache"
	"red-book-mgr/models"
	"red-book-mgr/pkg"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	cont := c.PostForm("cont")
	cate := c.PostForm("cate")
	if title == "" || cont == "" || cate == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容不能为空",
		})
		return
	}
	engin := models.Engin{
		Title: title,
		Cont:  cont,
		Cate:  cate,
	}
	err := models.DB.Create(&engin).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "Engin_id" + strconv.Itoa(int(engin.ID))
	var news models.Engin
	models.DB.Where("id = ?", engin.ID).First(&news)
	jsonEngin, _ := json.Marshal(news)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonEngin, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func List(c *gin.Context) {
	var list []models.Engin
	redis_key := "news_list"
	cacheEngin, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheEngin == "" {
		models.DB.Find(&list)
		jsonEngin, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonEngin, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheEngin), &list)
	}
	models.DB.Find(&list)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": list,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Delete(&models.Engin{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "news_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})

}
func Login(c *gin.Context) {
	name := c.Query("name")
	pass := c.Query("pass")
	var login models.User
	err := models.DB.Where("name = ?", name).First(&login).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "名称错误",
		})
		return
	}
	if pkg.Md5str(pass) != login.Pass {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}
